 package com.ghbank.rdws.batchservice.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ghbank.rdws.auth.entity.ModuleProcedure;
import com.ghbank.rdws.auth.entity.ModuleToken;
import com.ghbank.rdws.auth.repository.ModuleProcedureRepository;
import com.ghbank.rdws.auth.repository.ModuleTokenRepository;
import com.ghbank.rdws.batchservice.entity.BatchLog;
import com.ghbank.rdws.batchservice.enums.ProcedureType;
import com.ghbank.rdws.batchservice.repository.BatchLogRepository;
import com.ghbank.rdws.batchservice.service.BatchService;
import com.ghbank.rdws.common.command.ShellExecutor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class BatchServiceImpl implements BatchService {
    
    @Autowired
    private BatchLogRepository batchLogRepository;
    
    @Autowired
    private ModuleTokenRepository moduleTokenRepository;
    
    @Autowired
    private ModuleProcedureRepository moduleProcedureRepository;
    
    @Transactional
    @Override
    public int execute(BatchLog entity) throws Exception {
        //根据token和批次号执行程序
        Date date = new Date();
        ModuleToken moduleToken = moduleTokenRepository.findTopByTokenAndExpiresAfter(entity.getToken(), date);
        if (moduleToken == null) {
            log.info("没有找到有效的token为{}的模块",entity.getToken());
            throw new RuntimeException("没有找到有效的模块");
        }
        ModuleProcedure moduleProcedure = moduleProcedureRepository.findByfunctionId(moduleToken.getFunctionId());
        String procedure = moduleProcedure.getProcedure();
        String type = moduleProcedure.getProcedureType();
        if (!ProcedureType.SHELL.getName().equals(type)) {
            throw new RuntimeException("不支持的程序类型：" + type);
        } 
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("batchNum", entity.getBatchNum());
        int result = ShellExecutor.execute(procedure,params);
        batchLogRepository.save(entity);
        return result;
    }
}
